package com.appspot.moviesessions.provider;

import com.appspot.moviesessions.EventPublisher;

public class DatabaseFactoryImpl implements DatabaseFactory {

	private Database database;
	private EventPublisher eventPublisher;

	public DatabaseFactoryImpl(Database database) {
		this.database = database;
	}

	public DatabaseFactoryImpl(Database database, EventPublisher eventPublisher) {
		this.database = database;
		this.eventPublisher = eventPublisher;
		createTables();
	}

	public DatabaseFactoryImpl(Database database, EventPublisher publisher,
			int oldVersion, int newVersion) {
		this.database = database;
		this.eventPublisher = publisher;
		dropTables();
		createTables();
	}

	@Override
	public Database getDatabase() {
		return database;
	}

	private void createTables() {
		database.execSQL(String.format(
				"CREATE TABLE %s(%s INTEGER PRIMARY KEY,%s TEXT,%s TEXT)",
				MovieSession.Movie.TABLE, MovieSession.Movie._ID,
				MovieSession.Movie.NAME, MovieSession.Movie.POSTER_URI));
		database.execSQL(String.format(
				"CREATE TABLE %s(%s INTEGER PRIMARY KEY,%s TEXT)",
				MovieSession.Location.TABLE, MovieSession.Location._ID,
				MovieSession.Location.NAME));
		database.execSQL(String
				.format("CREATE TABLE %s(%s INTEGER PRIMARY KEY AUTOINCREMENT,%s INTEGER,%s INTEGER,%s INTEGER)",
						MovieSession.Session.TABLE, MovieSession.Session._ID,
						MovieSession.Session.MOVIE,
						MovieSession.Session.LOCATION,
						MovieSession.Session.TIME));
		eventPublisher.publish(new DatabaseCreatedEvent(database));
	}

	private void dropTables() {
		String dropStatement = "DROP TABLE IF EXISTS %s;";
		database.execSQL(String.format(dropStatement, MovieSession.Movie.TABLE));
		database.execSQL(String.format(dropStatement,
				MovieSession.Location.TABLE));
		database.execSQL(String.format(dropStatement,
				MovieSession.Session.TABLE));
	}

}
